﻿using ETA.ClientService;
using ETA.Common;
using ETA.DomainEnum;
using ETA.Dtos;
using ETA.Entity;
using ETA.IService;
using ETA.Web.App_Start;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace ETA.Web.Controllers
{
    /// <summary>
    /// 报名流程处理
    /// </summary>
    [AuthFilter("报名事物处理员")]
    public class RegistHandlerController : BaseController
    {

        private static IFlowStepService _IFlowStepService { set; get; }
        private static IFlowLogService _IFlowLogService { set; get; }
        private static IWebMessageService _IWebMessageService { set; get; }
        private static IWorkTypeService _IWorkTypeService { set; get; }
        private static IUserService _IUserService { set; get; }
        private static IRegistrationMainFormService _IRegistrationMainFormService { set; get; }
        private static IMBTIService _IMBTIService { set; get; }

        public RegistHandlerController(IFlowStepService IFlowStepService, IFlowLogService IFlowLogService, IWebMessageService IWebMessageService
              , IWorkTypeService IWorkTypeService, IUserService IUserService, IRegistrationMainFormService IRegistrationMainFormService,
            IMBTIService IMBTIService)
        {
            _IFlowStepService = IFlowStepService;
            _IFlowLogService = IFlowLogService;
            _IWebMessageService = IWebMessageService;
            _IWorkTypeService = IWorkTypeService;
            _IUserService = IUserService;
            _IRegistrationMainFormService = IRegistrationMainFormService;
            _IMBTIService = IMBTIService;
        }
        //
        // GET: /RegistHandler/

        public ActionResult Index()
        {
            var dropdownList = GetFlowStepDownList();
            ViewBag.flowStepList = dropdownList;
            return View();
        }

        public ActionResult GetFlowLogs(FlowLogFilter filter)
        {
            var count = 0;
            var res = _IFlowLogService.QueryFlowLog(new QueryFlowLogRequest
            {
                Page = filter.Page,
                PageSize = filter.PageSize,
                FlowLog = new Entity.FlowLog
                {
                    FlowStepId = filter.FlowStepId
                }
            }, out count);
            if (res.Result.IsSuccess)
            {
                // res.FlowLogs.ToList().ForEach(l => l.RegistrationMainForm.FlowLogs.Clear());
                res.OrgFlowLogs.Clear();
            }
            return JsonWithDate(res);
        }

        public ActionResult GetFlowLogsCount(FlowLogFilter filter)
        {
            var count = 0;
            var res = _IFlowLogService.QueryFlowLog(new QueryFlowLogRequest
            {
                Page = filter.Page,
                PageSize = filter.PageSize,
                FlowLog = new Entity.FlowLog
                {
                    FlowStepId = filter.FlowStepId
                }
            }, out count);
            return Json(count);
        }

        /// <summary>
        /// 获取页面步骤筛选下拉列表
        /// </summary>
        /// <returns></returns>
        private List<SelectListItem> GetFlowStepDownList()
        {
            var list = new List<SelectListItem>() { 
              new SelectListItem{
                 Text ="（全部）",
                 Value="-1",
                 Selected = true
              }
            };
            var rep = _IFlowStepService.QueryFlowStepList(new QueryFlowStepRequest());
            if (rep.Result.IsSuccess)
            {
                var flowSteps = rep.FlowSteps.OrderBy(s => s.FlowIndex);
                foreach (var step in flowSteps)
                {
                    list.Add(new SelectListItem
                    {
                        Text = step.FlowStepName,
                        Value = step.FlowStepId + ""
                    });
                }
            }
            if (list.Any())
            {
                var index = 1;
                list.ForEach(l =>
                {
                    if (l.Value != "-1")
                    {
                        l.Text = (index++) + "-" + l.Text;
                    }
                });
            }
            return list;
        }

        /// <summary>
        /// 提交到下一步 并发送站内消息
        /// </summary>
        /// <returns></returns>
        public ActionResult TransferLogToNextStep(string ids, DateTime sDate, DateTime eDate, string message)
        {
            var res = new Response
            {
                Result = new ResultDto
                {
                    IsSuccess = true
                }
            };
            if (!string.IsNullOrEmpty(ids))
            {
                var idArr = ids.Split('#');
                foreach (var id in idArr)
                {
                    if (!string.IsNullOrEmpty(id))
                    {
                        var tempRes = HandlerSigleLog(id, sDate, eDate, message);
                        if (!tempRes.Result.IsSuccess)
                        {
                            res.Result.IsSuccess = false;
                            res.Result.ErrMessage += tempRes.Result.ErrMessage;
                        }
                    }
                }

            }
            return JsonWithDate(res);
        }

        /// <summary>
        /// 处理单条记录
        /// </summary>
        /// <param name="flowLogId"></param>
        /// <param name="sDate"></param>
        /// <param name="eDate"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private Response HandlerSigleLog(string flowLogId, DateTime sDate, DateTime eDate, string message)
        {
            var res = new Response();
            var count = 0;
            var queryFlowlogRes = _IFlowLogService.QueryFlowLog(new QueryFlowLogRequest
            {
                FlowLog = new Entity.FlowLog
                {
                    FlowLogId = flowLogId
                }
            }, out count);

            if (queryFlowlogRes.Result.IsSuccess)
            {
                var log = queryFlowlogRes.OrgFlowLogs.FirstOrDefault();
                if (log != null)
                {
                    log.HandlerDate = DateTime.Now;
                    log.HandlerStateEnum = DomainEnum.HandlerStateEnum.已处理;
                    log.FlowLogStateEnum = DomainEnum.FlowLogStateEnum.完成;
                    log.ModifyDate = DateTime.Now;
                    res = _IFlowLogService.ModifyFlowLog(new ModifyFlowLogRequest
                    {
                        FlowLog = log
                    });

                    if (res.Result.IsSuccess)//发送消息
                    {
                        var nextFlowStepResponse = RegistrationMainFormBll.SubmitFlowLog(log.RegistrationMainForm.User.UserId, (log.FlowStepInfo.FlowIndex.Value + 1), FlowLogStateEnum.可开启);
                        if (!string.IsNullOrEmpty(nextFlowStepResponse.Result.Message))
                        {
                            res = _IWebMessageService.CreateWebMessage(new CreateWebMessageRequest
                             {
                                 WebMessage = new Entity.WebMessage
                                 {
                                     WebMessageId = Guid.NewGuid() + "",
                                     Content = message,
                                     SDate = sDate,
                                     EDate = eDate,
                                     MessageTypeEnum = DomainEnum.MessageTypeEnum.报名流程通知,
                                     RegistrationMainFormId = log.RegistrationMainForm.RegistrationMainFormId,
                                     UserId = log.RegistrationMainForm.User.UserId,
                                     FlowLogId = nextFlowStepResponse.Result.Message //此处为下一步流程id
                                 }
                             });
                        }
                        else
                        {
                            res.Result.ErrMessage = "新流程创建失败";
                            res.Result.IsSuccess = false;
                        }
                    }

                }
                else
                {
                    res.Result.ErrMessage = flowLogId + "数据未找到";
                    res.Result.IsSuccess = false;
                }
            }
            else
            {
                res.Result.ErrMessage += queryFlowlogRes.Result.ErrMessage;
                res.Result.IsSuccess = false;
            }
            return res;
        }

        public ActionResult InfoCheck(string flowLogId)
        {
            var count = 0;
            var queryFlowlogRes = _IFlowLogService.QueryFlowLog(new QueryFlowLogRequest
              {
                  FlowLog = new Entity.FlowLog
                  {
                      FlowLogId = flowLogId
                  }
              }, out count);

            if (queryFlowlogRes.Result.IsSuccess)
            {
                var log = queryFlowlogRes.OrgFlowLogs.FirstOrDefault();
                if (log != null)
                {
                    switch (log.FlowStepInfo.FlowStepName)
                    {
                        case "赴日技能实习生登记表":
                            return FillRegistrationFormCheck(log.RegistrationMainForm);
                        case "网上评定":
                            var queryMBTI = _IMBTIService.QueryMBTIList(new QueryMBTIRequest
                            {
                                MBTIModel = Config.OnlineTestKind,
                                UserId = log.RegistrationMainForm.User.UserId
                            });
                            var reportId = string.Empty;
                            if (queryMBTI.Result.IsSuccess && queryMBTI.MBTIs.Any())
                            {
                                reportId = queryMBTI.MBTIs.OrderBy(o=>o.CreateDate).LastOrDefault().ReportId;
                            }
                            return MBTICheck(reportId);
                    }
                }
            }
            return View();
        }

        /// <summary>
        /// 报表查看
        /// </summary>
        /// <param name="reportId"></param>
        /// <returns></returns>
        public ActionResult MBTICheck(string reportId)
        {
            ViewBag.ReportId = reportId;
            return View("MBTICheck");
        }

        public FileResult OutPutWord(string html)
        {
            byte[] fileContents = Encoding.Default.GetBytes(html);
            return File(fileContents, "application/ms-word", "用户报表.doc");
        }

        public ActionResult FillRegistrationFormCheck(RegistrationMainForm mainForms)
        {
            var user = mainForms.User;
            var basicInfo = new RegistrationBasicInfo();
            if (mainForms.RegistrationBasicInfos.Any())
            {
                ViewBag.EducationLevelEnum = ((Enum)EducationLevelEnum.无学历).
                    ToSelectListItem(mainForms.RegistrationBasicInfos.FirstOrDefault().EducationLevelEnum + "");
                basicInfo = mainForms.RegistrationBasicInfos.FirstOrDefault();
            }
            else
            {
                ViewBag.EducationLevelEnum = ((Enum)EducationLevelEnum.无学历).
                   ToSelectListItem();

            }
            ViewBag.WorkTypeList = GetWorkTypeList();
            return View("FillRegistrationFormCheck", mainForms);
        }

        /// <summary>
        /// 所有项目列表
        /// </summary>
        /// <returns></returns>
        public IEnumerable<WorkTypeDto> GetWorkTypeList()
        {
            IEnumerable<WorkTypeDto> workTypeList = null;
            var response = _IWorkTypeService.QueryWorkTypeList(new QueryWorkTypeRequest());
            if (response.Result.IsSuccess)
            {
                workTypeList = response.WorkTypeList;
            }
            return workTypeList;
        }
    }
}
